package com.xlzcx.xltz.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.xlzcx.xltz.filter.SkipLogin;
import com.xlzcx.xltz.utils.R;
import com.xlzcx.xltz.utils.SnowFlakeUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 作者: 李咨辰
 * 文件名: FileController.java
 * 路径: com.xlzcx.xltz.controller
 * 时间: 2024-10-18 16:56
 * 版本: 1.0
 * 描述: TODO 文件处理
 **/
@RestController
@RequestMapping("/file")
public class FileController {


    /**
     * 添加图片
     *
     * @param file 图片对象
     * @return 图片路径
     */
    @SkipLogin
    @PostMapping("/upload")
    public R imageUpload(MultipartFile file) throws IOException {
        File document = new File(System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename());
        file.transferTo(document);  // 将MultipartFile内容写入文件
        String path = "upload/" + new SimpleDateFormat("yyyy/MM/dd/HH").format(new Date());//路径
        long fileName = SnowFlakeUtil.getFlowIdInstance().nextId();//文件名
        String substring = document.getName().substring(document.getName().lastIndexOf('.'));//后缀
        String objectName = path + "/" + fileName + substring;

        OSS ossClient = new OSSClientBuilder().build("https://oss-cn-hangzhou.aliyuncs.com",
                "LTAI5tM88xx9GjQ1mhdvRkhj",
                "Nxz5EfUowTqd5hYln4tbDv2GaQR436");
        PutObjectRequest putObjectRequest = new PutObjectRequest("item-kf", objectName, document);
        ossClient.putObject(putObjectRequest);
        return R.ok().put("data", objectName);
    }
}
